﻿using AutoMapper;
using FlyleafLib.MediaFramework.MediaPlaylist;
using Morin.Services;
using Morin.Shared.Common;
using Morin.Shared.Models;
using Morin.Wpf.Messages.Players;
using Stylet;
using static System.Net.Mime.MediaTypeNames;
using System.Text.RegularExpressions;

namespace Morin.Wpf.ViewModels.Players;

public class PlayerListViewModel(IAppService appService, IMapper mapper, IEventAggregator eventAggregator) : Screen
{
    public required PlayMode PlayMode { get; set; } = PlayMode.Video;
    public required BindableCollection<VideoModel> Videos { get; set; }
    private readonly IAppService appService = appService;
    private readonly IMapper mapper = mapper;
    private readonly IEventAggregator eventAggregator = eventAggregator;
    private bool videosSortByAsc;

    public bool VideosSortByAsc
    {
        get => videosSortByAsc;
        set
        {
            videosSortByAsc = value;
            //  倒序显示
            if (PlayList != null)
            {
                PlayList = !value
                    ? PlayList.OrderByDescending(x => x.Sort).ToList()
                    : PlayList.OrderBy(x => x.Sort).ToList();
                Videos = [.. PlayList];
            }
        }
    }

    /// <summary>
    /// 播放清单
    /// </summary>
    public required List<VideoModel> PlayList { get; set; }
    private int playlistIndex;
    private VideoModel videoItem=new();

    public VideoModel VideoItem
    {
        get => videoItem;
        set
        {
            videoItem = value;
            if (value != null)
            {
                //  通知播放器播放
                EpisodeChangedAsync(value);

                //  更新历史观看
                var history = mapper.Map<HistoryViewsModel>(value);
                appService.HistoryViewsAddOrUpdate(history);

                //  当前播放列表的下标
                playlistIndex = PlayList.IndexOf(value);
            }
        }
    }

    private string line="";

    public required string Line
    {
        get => line;
        set
        {
            line = value;

            switch (this.PlayMode)
            {
                case PlayMode.Video:
                    {
                        if (PlayDict == null) break;
                        //  倒序显示
                        PlayList = !VideosSortByAsc
                            ? PlayDict[value].OrderByDescending(x => x.Sort).ToList()
                            : PlayDict[value].OrderBy(x => x.Sort).ToList();
                        Videos = [.. PlayList];

                        //  设置最后观看
                        var historyViews = appService.GetHistoryViews(Videos[0].VodSourceID, Videos[0].VodId);
                        VideoItem = GetLastView(PlayList, historyViews);
                        break;
                    }
                default:
                    {
                        if (PlayDict == null) break;
                        PlayList = PlayDict[value].ToList();
                        if (PlayList.Count > 0) VideoItem = PlayList[0];
                        break;
                    }
            }
        }
    }



    public required List<string> Lines { get; set; }
    private Dictionary<string, string> LineDict = [];

    public Dictionary<string, IEnumerable<VideoModel>>? PlayDict { get; set; } = [];

    protected override void OnInitialActivate()
    {
        base.OnInitialActivate();
        //  播放视频
        switch (PlayMode)
        {
            case PlayMode.Video:
                SetVideoLineInfoAsync();
                break;
            case PlayMode.TV:
                SetTVLineInfoAsync();
                break;
            case PlayMode.LIVE:
                break;
            default:
                break;
        }
    }
    private VideoModel GetLastView(IEnumerable<VideoModel> videos, IEnumerable<HistoryViewsModel> historyViews)
    {
        if (!historyViews.Any()) return videos.First();

        var lastViewModel = historyViews.MaxBy(x => x.ViewTime);
        if (lastViewModel != null)
            return videos.FirstOrDefault(x =>
                x.VodSourceID == lastViewModel.VodSourceID && x.VodId == x.VodId && x.Episode != null &&
                x.Episode.Equals(lastViewModel.Episode)) ?? videos.First();
        return new VideoModel();
    }
    private Task SetTVLineInfoAsync()
    {
        if (PlayDict == null) return Task.CompletedTask;

        return Task.Run(() =>
        {
            Lines = [.. PlayDict.Keys];

            //  默认显示 
            if (Lines.Count > 0) Line = Lines[0];
        });
    }

    private Task SetVideoLineInfoAsync()
    {
        if (PlayDict == null) return Task.CompletedTask;

        Lines = [.. PlayDict?.Keys];
        //  默认显示 
        if (Lines.Count > 0) Line = Lines[0];
        return Task.FromResult(Lines);
    }

    public Task EpisodeChangedAsync(VideoModel videoItem, CancellationToken cancellationToken = default)
    {
        if (videoItem == null) return Task.CompletedTask;
        if (string.IsNullOrEmpty(videoItem.VodPlayUrl)) return Task.CompletedTask;

        return Task.Run(async () =>
        {
            //  判断播放连接结尾是否为m3u8
            if (!videoItem.VodPlayUrl.EndsWith("m3u8"))
            {
                var content = await HttpsProvider.GetAsync(videoItem.VodPlayUrl);
                if (string.IsNullOrEmpty(content)) return Task.CompletedTask;
                string pattern = @"https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+/[^\s'""<>()\[\]]+\.m3u8";
                MatchCollection matches = Regex.Matches(content, pattern);
                if (matches.Count > 0)
                {
                    videoItem.VodPlayUrl = matches[0].Value;
                }
            }
            eventAggregator.Publish(new OnEpisodeChangedMessage { Model = videoItem });
            return Task.CompletedTask;
        });
    }

    public void NavigateBefore()
    {
        SetPlayPosition(playlistIndex, true, VideosSortByAsc);
    }

    public void NavigateNext()
    {
        SetPlayPosition(playlistIndex, false, VideosSortByAsc);
    }

    private void SetPlayPosition(int index, bool beforeOrNext, bool asc)
    {
        if (PlayList != null && PlayList.Count > 0)
        {
            if (asc && beforeOrNext) //  倒序，下一个
            {
                index--;
                if (index < 0) index = 0;
            }
            else if (!asc && beforeOrNext) //  正序，下一个
            {
                index++;
                if (index == PlayList.Count) index = PlayList.Count - 1;
            }
            else if (asc && !beforeOrNext) //  倒序，上一个
            {
                index++;
                if (index == PlayList.Count) index = PlayList.Count - 1;
            }
            else if (!asc && !beforeOrNext) //  正序，上一个
            {
                index--;
                if (index < 0) index = 0;
            }

            VideoItem = PlayList[index];
        }
    }
}